package edu.gatech.gitmad.catbug.formation;


import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;


public class HTTPPost {
	private URL url;
	private ArrayList<String> vars;
	private ArrayList<String> vals;
	private Thread thread;
	
	public HTTPPost() {
		vars = new ArrayList<String>();
		vals = new ArrayList<String>();
	}
	
	public HTTPPost(URL url, String[] vars, String[] vals) {
		this();
		this.url = url;
		
		for (int i=0; i<vars.length; i++) {
			if (vars[i] != null && vals[i] != null) {
				this.vars.add(vars[i]);
				this.vals.add(vals[i]);
			}
		}
	}
	
	public HTTPPost(String urlString, String[] vars, String[] vals) {
		this();
		try {
			this.url = new URL(urlString);
		}
		catch (MalformedURLException e) {
			e.printStackTrace();
			System.exit(0);
		}
		
		for (int i=0; i<vars.length; i++) {
			if (vars[i] != null && vals[i] != null) {
				this.vars.add(vars[i]);
				this.vals.add(vals[i]);
			}
		}
	}
	
	public void execute() {
		thread = new Thread(new NetworkOperation());
		thread.start();
	}
	
	public void waitForThis() {
		if (thread != null) {
			try {
				thread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	private class NetworkOperation implements Runnable {
		public void run() {
			String content = "";
			for (int i=0; i<vars.size(); i++) {
				if (i != 0)
					content += "&";
				content += vars.get(i) + "=" + vals.get(i);
			}
			HttpURLConnection conn = null;
			try {
				conn = (HttpURLConnection)url.openConnection();
				conn.setRequestMethod("POST");
				conn.setDoOutput(true);
				conn.setDoInput(true);
				conn.setInstanceFollowRedirects(false);
				//BrowserInfo.cookieJar.giveCookies(conn);
				OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
				out.write(content);
				out.flush();
				out.close();
				//BrowserInfo.cookieJar.updateFrom(conn);
			}
			catch (IOException e) {
				e.printStackTrace();
				System.exit(0);
			}
			conn.disconnect();
			if (thread != null) {
				thread = null;
			}
		}
	}

}
